package com.yhq.basic.thread.juc;

import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Exchanger;

/**
 * @author hqyin
 * @date 2025/5/13 4:34 PM
 */
public class TestExchanger {

    public static void main(String[] args) {
        new Thread(new producer(),"producer").start();
        new Thread(new Consumer(),"consumer").start();

    }
    private static ArrayBlockingQueue<String>  arr1 = new ArrayBlockingQueue(5);

    private static ArrayBlockingQueue<String>  arr2 = new ArrayBlockingQueue(5);

    private static Exchanger<ArrayBlockingQueue> exchanger = new Exchanger<>();

    static class producer implements Runnable {
        @Override
        public void run() {
            ArrayBlockingQueue<String>  curr = arr1;
            while (true) {
                try {
                    String str= UUID.randomUUID().toString();
                    curr.add(str);
                    System.out.println("生产者：生产=>"+str);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    System.out.println("生产者：队列满了");
                    try {
                        curr = exchanger.exchange(curr);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                    System.out.println("生产者：换了一个空队列");
                }
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            ArrayBlockingQueue<String>  curr = arr2;
            while (true) {
                String str = curr.poll();
                if(str!= null) {
                    System.out.println("消费者：取出=>"+str);
                } else {
                    System.out.println("消费者：消费完了");
                    try {
                        curr = exchanger.exchange(curr);
                        System.out.println("消费者：切换队列");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
